package com.example.actordemo3.total;

import akka.actor.AbstractActor;
import akka.cluster.Cluster;
import akka.cluster.ClusterEvent;
import akka.cluster.Member;

public class WordCountService extends AbstractActor {
    Cluster cluster = Cluster.get(getContext().system());

    @Override
    public void preStart() throws Exception {
        System.out.println("开始 "+getSelf());
        cluster.subscribe(getSelf(), ClusterEvent.MemberUp.class);
    }

    @Override
    public void postStop() throws Exception {
        cluster.unsubscribe(getSelf());
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder().match(Article.class,msg->{
            System.out.println("当前节点"+cluster.selfAddress()+"self="+getSelf()+"正在处理");
            Article art = msg;
            String content = art.getContent();
            int length = content.split("").length;
            getSender().tell(new CountResult(art.getId(),length),getSelf());
        }).match(ClusterEvent.MemberUp.class,msg->{
            System.out.println("--------------------------------------------");
            ClusterEvent.MemberUp mu = msg;
            Member member = mu.member();
            if(member.hasRole("wordFrontend")){
                getContext().actorSelection(member.address()+"/user/wordFrontService")
                        .tell("serviceIsOk",getSelf());
                System.out.println(member+"is up");

            }else {
                System.out.println(member+"is  service up");
            }

        }).matchAny(o->{
            unhandled(o);
        }).build();
    }
}
